package com.woniuxy.creditsystem.systemmag.util;

import org.apache.commons.io.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.File;
import java.net.URLEncoder;

public class GetBinaryStream {
    public static ResponseEntity<byte[]> getStream(String fileName,String userAgent){
        File file = new File(fileName);
        if(file.exists()){
            try{
                //构建一个响应状态码 200
                ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
                //设置文件的长度
                builder.contentLength(file.length());
                //告诉前端，后端现在给你的数据类型是：二进制流
                builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
                fileName = URLEncoder.encode(fileName, "UTF-8");
                //判断浏览器是否是IE浏览器
                if(userAgent.indexOf("MSIE") > 0) {
                    builder.header("Content-Disposition", "attachment; filename=" + fileName);
                }else {
                    builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + fileName);
                }

                //通过FileUtils工具类，读取文件到 响应体中
                return builder.body(FileUtils.readFileToByteArray(file));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

    public static ResponseEntity<byte[]> getStreamTwo(String fileName,String userAgent){
        String filePath = "E://img" + File.separator + fileName;
        File file = new File(filePath);
        if(file.exists()){
            try{
                //构建一个响应状态码 200
                ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
                //设置文件的长度
                builder.contentLength(file.length());
                //告诉前端，后端现在给你的数据类型是：二进制流
                builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
                fileName = URLEncoder.encode(fileName, "UTF-8");
                //判断浏览器是否是IE浏览器
                if(userAgent.indexOf("MSIE") > 0) {
                    builder.header("Content-Disposition", "attachment; filename=" + fileName);
                }else {
                    builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + fileName);
                }

                //通过FileUtils工具类，读取文件到 响应体中
                return builder.body(FileUtils.readFileToByteArray(file));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }
}
